package net.ck.hzq;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;

import Bean.ShareBean;
import Bean.ShareParamBean;
import Utils.CheckPhoneNumberUtils;
import Utils.HelloWordModel;
import Utils.ResourcesManager;
import Utils.SystemDatas;
import base.BaseActivity;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import event.LoginEvent;
import retrofit2.Call;
import retrofit2.Response;

public class ShareActivity extends BaseActivity implements View.OnClickListener, Handler.Callback {

    private ImageView share_back, share_image;

    private TextView share_txt_recommendationcode, share_txt_referee, share_txt_phonenumber;


    private Button share_but_invitation;

    private Handler handler;

    private Context context;

    private SharedPreferences sp;

    private String title, content, url;

    private Bitmap bitmap;

    @Override
    public int getLayoutId() {
        return R.layout.activity_share;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        showProgressDialog();
//        TobuyApplication.getmInstance().onActivityCreate(this);
        sp = getSharedPreferences("ToBuy", Context.MODE_PRIVATE);

        context = ShareActivity.this;
        handler = new Handler(Looper.getMainLooper(), this);

        share_back = (ImageView) findViewById(R.id.share_back);
        share_txt_recommendationcode = (TextView) findViewById(R.id.share_txt_recommendationcode);
        share_image = (ImageView) findViewById(R.id.share_image);
        share_txt_referee = (TextView) findViewById(R.id.share_txt_referee);
        share_txt_phonenumber = (TextView) findViewById(R.id.share_txt_phonenumber);
        share_but_invitation = (Button) findViewById(R.id.share_but_invitation);
        share_back.setOnClickListener(this);
        share_but_invitation.setOnClickListener(this);

        ShareParamBean s = new ShareParamBean();
        s.setCustomId(Integer.parseInt(sp.getString("id", null)));
        Call<ShareBean> userMsgCall = HelloWordModel.getInstance(context).getShare(SystemDatas.GetService_URL("getshare"), s);//, sp.getString("token", null)
        userMsgCall.enqueue(new retrofit2.Callback<ShareBean>() {
            @Override
            public void onResponse(Call<ShareBean> call, final Response<ShareBean> response) {
                dismissProgressDialog();
                try {
                    if (response.body() != null && "401".equals(response.body().getResult())) {
                        EventBus.getDefault().post(new LoginEvent());
                    } else if (response.body().getMsg().equals("success")) {
                        try {
                            String s[] = response.body().getData().getImg().split("base64,");
                            bitmap = CheckPhoneNumberUtils.stringtoBitmap(s[1]);
                            share_image.setImageBitmap(bitmap);
                            share_txt_recommendationcode.setText(response.body().getData().getCustom().getRecommendationCode());
                            share_txt_referee.setText(response.body().getData().getCustom().getRealName());
                            share_txt_phonenumber.setText(response.body().getData().getCustom().getPhoneNumber());
                            title = response.body().getData().getMaintitle();
                            content = response.body().getData().getSubtitle();
                            url = response.body().getData().getUrl();
                        } catch (Exception e) {

                        }
                    } else {
                        showFailureTipDialog(response.body().getMsg());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(Call<ShareBean> call, Throwable t) {
                dismissProgressDialog();
                showFailureTipDialog("获取分享信息错误，请稍后重试");
            }
        });

//        String textContent = share_txt_recommendationcode.getText().toString();
//        mBitmap = CodeUtils.createImage(textContent, 400, 400, BitmapFactory.decodeResource(getResources(), R.drawable.logo));
//        share_image.setImageBitmap(mBitmap);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.share_back:
                finish();
                break;
            case R.id.share_but_invitation:
                onOneKeyShare();
                break;
        }
    }

    /**
     * 一键分享
     */
    private void onOneKeyShare() {



//        Platform.ShareParams sp = new Platform.ShareParams();
//        sp.setTitle("测试分享的标题");
//// 标题的超链接
//        sp.setTitleUrl("http://sharesdk.cn");
//        sp.setText("测试分享的文本");
//        sp.setImageUrl("http://www.someserver.com/测试图片网络地址.jpg");
//        Platform qq = ShareSDK.getPlatform (QQ.NAME);
//// 设置分享事件回调（注：回调放在不能保证在主线程调用，不可以在里面直接处理UI操作）
//        qq.setPlatformActionListener (new PlatformActionListener() {
//            public void onError(Platform arg0, int arg1, Throwable arg2) {
//                // 失败的回调，arg:平台对象，arg1:表示当前的动作(9表示分享)，arg2:异常信息
//            }
//            public void onComplete(Platform arg0, int arg1, HashMap arg2) {
//                // 分享成功的回调
//            }
//            public void onCancel(Platform arg0, int arg1) {
//                // 取消分享的回调
//            }
//        });
//// 执行分享
//        qq.share(sp);






        //TODO
//        ResourcesManager.getInstace(MobSDK.getContext());
        cn.sharesdk.onekeyshare.OnekeyShare oks = new cn.sharesdk.onekeyshare.OnekeyShare();
        oks.setAddress("http://www.tobuy.net/");
        ResourcesManager manager = ResourcesManager.getInstace(context);
//        if (!TextUtils.isEmpty(manager.getFilePath())) {
//            oks.setFilePath(manager.getFilePath());
//        } else {
//            oks.setFilePath(manager.getFilePath());
//        }
        oks.setTitle(title);//标题
        oks.setText(content);//内容
        oks.setUrl(url);//链接
        oks.setTitleUrl(url);
        oks.setImageData(bitmap);
//        oks.setImageUrl(s);//图标
//        String customText = manager.getText();
//		if (customText != null) {
//			oks.setText(customText);
//		} else if (manager.getText() != null && manager.getText().contains("0")) {
//			oks.setText(manager.getText());
//		} else {
//		}
//        oks.setComment(manager.getComment());
//        oks.setSite(manager.getSite());
//        oks.setSiteUrl(manager.getSiteUrl());
//        oks.setVenueName(manager.getVenueName());
//        oks.setVenueDescription(manager.getVenueDescription());
//        oks.setSilent(true);
//        oks.setLatitude(23.169f);
//        oks.setLongitude(112.908f);
        oks.setCallback(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                String msg = ResourcesManager.actionToString(i);
                String text = platform.getName() + " completed at " + msg;
                Message message = new Message();
                message.obj = text;
//                handler.sendMessage(message);
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                String msg = ResourcesManager.actionToString(i);
                String text = platform.getName() + "caught error at " + msg;
                Message message = new Message();
                message.obj = text;
//                handler.sendMessage(message);
            }

            @Override
            public void onCancel(Platform platform, int i) {
                String msg = ResourcesManager.actionToString(i);
                String text = platform.getName() + " canceled at " + msg;
                Message message = new Message();
                message.obj = text;
//                handler.sendMessage(message);
            }
        });
//        Bitmap logo = BitmapFactory.decodeResource(context.getResources(), R.drawable.logo);
//        String label = context.getString(R.string.app_name);
//        View.OnClickListener listener = new View.OnClickListener() {
//            public void onClick(View v) {
//                String text = "Customer Logo -- ShareSDK ";
//                Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
//            }
//        };
//        oks.setCustomerLogo(logo, label, listener);
        oks.show(context);
    }

    @Override
    public boolean handleMessage(Message msg) {
        String toastMsg = (String) msg.obj;
        Toast.makeText(ShareActivity.this, toastMsg, Toast.LENGTH_SHORT).show();
        return false;
    }

}
